﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HyEduOnline.Entities;
using HyEduOnline.Server.Teacher;
using WebSite.Models;
using System.IO;
using HyEduOnline.Server.Common;
using HyEduOnline.Server.Admin;
using HyEudOnline.Server.Common;
using HyEduOnline.Models;
using System.Data;
using HyEduOnline.Data;
using HyEduOnline.Server.Student;

namespace WebSite.Areas.WebApi.Controllers
{
    public class TeacherController : TeachersController
    {

        private TeachersDAO teachersDAO = new TeachersDAO();



        /// <summary>
        /// 教师个人信息更新
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="pk"></param>
        /// <returns></returns>
        public int TeaUpdate(string name, string value, string pk)
        {
            int id = frontCurrentTea.GetUserID();
            TbTeachers temp = teachersDAO.GetByID(id);
            ClassValueCopier.SetValue(temp, name, value);
            teachersDAO.Update(temp);

            return 0;
        }



        /// <summary>
        /// 修改密码时，验证当前密码
        /// </summary>
        /// <param name="Password"></param>
        /// <returns></returns>
        public int CheckPassword(string Password)
        {
            if (!string.IsNullOrEmpty(Password))
            {
                Password = Utitil.MD5(Password);//对密码加密
                int id = frontCurrentTea.GetUserID();
                TbTeachers tea = teachersDAO.GetByID(id);
                if (tea.SPassWord.Equals(Password))
                    return 1;//验证成功
                else
                    return 0;
            }
            return 1;
        }

        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="Password"></param>
        /// <returns></returns>
        public int UpdatePassword(string Password)
        {
            int id = frontCurrentTea.GetUserID();
            TbTeachers tea = teachersDAO.GetByID(id);
            tea.SPassWord = Utitil.MD5(Password);
            teachersDAO.Update(tea);
            return 1;
        }


        /// <summary>
        /// return all tree
        /// </summary>
        /// <returns></returns>
        public JsonResult TreeAll(int iDeanCourseId)
        {


            IList<TbTeaCatalog> items = new TeaCatalogDAO().getByPageDataBase(0, int.MaxValue, "ILevel ASC,I_ParentID ASC,Id ASC", "I_DeanCourseID=" + iDeanCourseId, out totalCount);//按ILevel升级，再按ParentID排序

            IList<zTreeNode> zNodes = new List<zTreeNode>();



            //写入根结点
            zTreeNode myNode = new zTreeNode();
            myNode.name = "根结点";
            myNode.open = true;

            myNode.id = 0;
            myNode.pId = -1;
            zNodes.Add(myNode);


            for (int i = 0; i < items.Count; i++)
            {
                myNode = new zTreeNode();

                myNode.name = items[i].STitle;
                myNode.open = false;

                myNode.id = items[i].Id;
                myNode.pId = (int)items[i].IParentId;
                myNode.tip = items[i].STitle;
                if (items[i].ILevel != null && items[i].ILevel < 2) myNode.open = true;//自动扩展1,2级
                zNodes.Add(myNode);

            }



            return Json(zNodes, JsonRequestBehavior.AllowGet);

        }


        /// <summary>
        /// 新增树结点,新增后返回所有的树结点
        /// </summary>
        /// <param name="parentID">需要新增结点的父结点，可以是0(根结点)</param>
        /// <returns>返回所有树结点</returns>
        [HttpPost]
        public int AddTreeNode(int id, int CourseId)
        {

            TbTeaCatalog tmpNode = new TbTeaCatalog();
            tmpNode.IParentId = id;//此处的id为parentid
            tmpNode.IDeanCourseId = CourseId;
            tmpNode.STitle = "新增结点";
            if (id != 0)
            {
                //非一级节点,先读取父结点
                TbTeaCatalog parentNode = new TeaCatalogDAO().GetByID(id);
                if (parentNode != null)
                {
                    tmpNode.ILevel = parentNode.ILevel + 1;
                }
                else
                {
                    return -1;
                    //Request.CreateResponse(HttpStatusCode.BadRequest, "出错了，找不到新建 TeaCatalog 的 父结点:"+id+"!!");
                }
            }
            else
            {
                //一级节点
                tmpNode.ILevel = 1;
            }


            new TeaCatalogDAO().Insert(tmpNode);

            return tmpNode.Id;

        }


        /// <summary>
        /// 获取资源目录
        /// </summary>
        /// <returns></returns>
        public JsonResult GetResourceDict()
        {
            TeaSourceDictDAO DictDAO = new TeaSourceDictDAO();
            List<TbTeaSourceDict> list = DictDAO.GetByPage("I_ParentID=" + 0, 0, int.MaxValue).ToList();
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 修改阅卷状态
        /// </summary>
        /// <param name="paperId"></param>
        /// <param name="stuCode"></param>
        /// <returns></returns>
        public int ReadPaper(int paperId, string stuCode)
        {
            TestScoresDAO testScoresDAO = new TestScoresDAO();
            TbTestScores stuScore = testScoresDAO.GetByPage("S_StuCode='" + stuCode + "' and I_PaperID=" + paperId, 0, int.MaxValue)[0];
            stuScore.IIsRead = 1;
            testScoresDAO.Update(stuScore);
            return 1;
        }


        public JsonResult analysePaper(int paperId, string classCode)
        {
            if (string.IsNullOrEmpty(classCode))
                return Json("1");
            int count = 0;
            string digitalStr = "";
            int[] digital = new int[12];//前十个数字代表每个分数段人数，第十一个代表考试人数，第十二个代表挂科人数
            TList<TbTestScores> scoreList = new TestScoresDAO().GetByPage(
                "I_PaperID=" + paperId + " and S_ClassCode='" + classCode + "'", 0, int.MaxValue, "ID", "DESC", out count);
            digital[10] = count;//当前班级人数
            foreach (var item in scoreList)
            {
                int score = (int)item.IScore;
                if (score < 10) { digital[0]++; digital[11]++; }
                if (score >= 10 && score < 20) { digital[1]++; digital[11]++; }
                if (score >= 20 && score < 30) { digital[2]++; digital[11]++; }
                if (score >= 30 && score < 40) { digital[3]++; digital[11]++; }
                if (score >= 40 && score < 50) { digital[4]++; digital[11]++; }
                if (score >= 50 && score < 60) { digital[5]++; digital[11]++; }
                if (score >= 60 && score < 70) { digital[6]++; }
                if (score >= 70 && score < 80) { digital[7]++; }
                if (score >= 80 && score < 90) { digital[8]++; }
                if (score >= 90 && score <= 100) { digital[9]++; }
            }
            foreach (var item in digital)
            {
                digitalStr = digitalStr + "," + item;
            }
            digitalStr = digitalStr.Substring(1, digitalStr.Length - 1);
            return Json(digitalStr);
        }


        /// <summary>
        /// 首页获取公告,邮箱
        /// </summary>
        /// <returns></returns>
        public JsonResult Search()
        {
            int totalCount = 0;  //总的数据记录条数I_NoticesType
            string condition = "I_NoticesType = 1" + "or I_NoticesType=3";//+ FrontUserInfo.GetUserType()
            IList<TbNotices> noticeList = new NoticesDAO().GetByPage(condition, 0, 5, "DSendTime", "DESC", out totalCount);
            condition = "I_IsRead=0 and S_RecNo='" + frontCurrentTea.GetNo() + "'";
            IList<VwEmail> emailList = new VwEmailDAO().GetByPageVW(condition, 0, 5, "DSendTime DESC", out totalCount);
            return Json(
                new
                {
                    noRead = totalCount,
                    notices = noticeList,
                    emails = emailList
                });
        }

        /// <summary>
        /// 修改课程介绍
        /// </summary>
        /// <param name="con">新内容</param>
        /// <param name="courseID"></param>
        /// <returns></returns>
        public int ModifyContent(TbDeanCourse temp)
        {
            if (temp.SIntro != null)
            {
                DeanCourseDAO courese = new DeanCourseDAO();
                TbDeanCourse cour = courese.GetByID(temp.Id);
                cour.SIntro = temp.SIntro;
                courese.Update(cour);
                return 1;
            }
            return 0;
        }

        /// <summary>
        /// 获取教师交的班级
        /// </summary>
        /// <param name="TeaCode"></param>
        /// <param name="CourseId"></param>
        /// <param name="TermId"></param>
        /// <returns></returns>
        public JsonResult GetClass(int CourseId, int TermId = 1)
        {
            //调用存储过程得到数据集
            string TeaCode = frontCurrentTea.GetNo();
            DataSet classDSTemp = DataRepository.Provider.TbDeanStuSelCourseProvider.selClass(TeaCode, CourseId, TermId);
            DataTable classDTTemp = classDSTemp.Tables[0];
            List<TbDeanStuSelCourse> classList = new List<TbDeanStuSelCourse>();
            //循环表的每一行
            foreach (DataRow item in classDTTemp.Rows)
            {
                TbDeanStuSelCourse stuClass = new TbDeanStuSelCourse();
                stuClass.IClassId = int.Parse(item[0].ToString());
                stuClass.SClassCode = item[1].ToString();
                stuClass.SClassName = item[2].ToString();
                classList.Add(stuClass);
            }
            TList<TbTeaCatalog> cataList = new TeaCatalogDAO().GetByPage("I_DeanCourseID=" + CourseId, 0, int.MaxValue);
            return Json(new { cla = classList, cata = cataList });
        }


        //新增一条练习
        public string AddPractice(int CourseId, string cataId, string PraName)
        {
            TeaCatalogDAO caDAO = new TeaCatalogDAO();
            StuPracticeListDAO praDao = new StuPracticeListDAO();
            TbStuPracticeList pra = new TbStuPracticeList();
            DateTime now = DateTime.Now;//当期时间
            int id = 0;
            int count = 0;
            string[] catalogList = cataId.Split(new char[] { ',' });//分离章节Id
            if (string.IsNullOrEmpty(PraName))
            {
                //练习名字由章节名决定 eg.第一章 第二章
                foreach (var item in catalogList)
                {
                    int caId = int.Parse(item);
                    int parentId = 0;
                    string Zname = "";
                    TbTeaCatalog caTemp = caDAO.GetByID(caId);
                    string name = caTemp.SCaptailName;//找到节名
                    //找到所属章名
                    parentId = (int)caTemp.IParentId;
                    if (parentId != 0)
                        Zname = caDAO.GetByID(parentId).SCaptailName;
                    name = Zname + "." + name;
                    PraName = PraName + " " + name;//拼凑所有的章节名
                }
            }
            pra.SPracticeName = PraName;
            pra.ICourseId = CourseId;
            pra.ITeaId = frontCurrentTea.GetUserID();
            pra.STeaCode = frontCurrentTea.GetNo();
            pra.DCreateTime = now;
            pra.ITotal = 100;
            pra.SCatalog = cataId;
            pra.STeaName = frontCurrentTea.GetUserName();
            praDao.Insert(pra);//插入到数据库表Tb_StuPracticeList

            TList<TbStuPracticeList> temp = praDao.GetByPage(
                "S_Catalog='" + cataId + "' and I_TeaID=" + pra.ITeaId, 0, int.MaxValue, "DCreateTime", "DESC", out count);

            if (temp.Count != 0)
            {
                id = temp[0].Id;
                return id + ":" + PraName;
            }
            else
                return null;
        }

        /// <summary>
        /// 添加参加练习的学生
        /// </summary>
        /// <param name="cataId"></param>
        /// <param name="claCode"></param>
        /// <param name="CourseId"></param>
        /// <param name="PraName"></param>
        /// <returns></returns>
        public int Practice(string cataId, string claCode, int CourseId, string PraName)
        {

            //若没选章节和目录,结束函数,返回-1
            if (string.IsNullOrEmpty(cataId))
                return -1;
            //若未选班级，返回-2
            if (string.IsNullOrEmpty(claCode))
                return -2;
            //添加一个练习
            //若添加练习题详细信息失败，则不继续操作
            int teaId = frontCurrentTea.GetUserID();//取教师的Id
            string teaCode = frontCurrentTea.GetNo();//取教师的工号
            StuPracticeResultDAO praRes = new StuPracticeResultDAO();
            string pracInfor = AddPractice(CourseId, cataId, PraName);
            if (string.IsNullOrEmpty(pracInfor))
                return 0;
            string[] pracInforList = pracInfor.Split(new char[] { ':' });

            string[] classCode = claCode.Split(new char[] { ',' });//分离班级编号

            string[] catalogList = cataId.Split(new char[] { ',' });//分离章节Id
            //添加选中的班级学生
            foreach (var item in classCode)
            {
                string where = "I_CourseID=" + CourseId + " and I_TeacherID=" + teaId + " and S_ClassCode='" + item + "'";
                //找出选了该课程，并且是当前班级的学生
                TList<TbDeanStuSelCourse> sel = new DeanStuSelCourseDAO().GetByPage(where, 0, int.MaxValue);
                TList<TbStuPractice> stuList = new TList<TbStuPractice>();
                //将每个学生添加到练习表
                foreach (var stu in sel)
                {
                    TbStuPractice tempStu = new TbStuPractice();
                    ClassValueCopier.Copy(tempStu, stu);
                    tempStu.IComplete = 0;
                    tempStu.ITeaId = teaId;
                    tempStu.STeaCode = teaCode;
                    tempStu.IPracticeId = int.Parse(pracInforList[0]);
                    tempStu.SPracticeName = pracInforList[1];
                    tempStu.IScore = 0;
                    tempStu.SStuCode = stu.SStuNo;
                    TbStudents st = new StudentsDAO().findBySNo(stu.SStuNo)[0];
                    tempStu.IStuId = st.Id;
                    stuList.Add(tempStu);

                    //查找练习结果的表
                    string resStr = "I_StuId=" + st.Id + " and I_CourseId=" + CourseId
                        + " and I_TeaId=" + teaId;
                    TList<TbStuPracticeResult> resList = praRes.GetByPage(resStr, 0, int.MaxValue);
                    TbStuPracticeResult stuRes = new TbStuPracticeResult();
                    //若不是第一次添加，更新
                    if (resList.Count > 0)
                    {
                        stuRes = resList[0];
                        stuRes.IIncomplete += 1;
                        stuRes.ITotal += 1;
                        praRes.Update(stuRes);
                    }
                    //第一次添加,插入
                    else
                    {

                        stuRes.IStuId = st.Id;
                        stuRes.SStuNo = st.SNo;
                        stuRes.SStuName = st.SName;
                        stuRes.ICourseId = CourseId;
                        stuRes.ITeaId = teaId;
                        stuRes.IComplete = 0;
                        stuRes.IIncomplete = 1;
                        stuRes.ITotal = 1;
                        praRes.Insert(stuRes);
                    }

                }
                new StuPracticeDAO().Insert(stuList);//插入到Tb_StuPractice
            }
            return 1;

        }
        /// <summary>
        /// 改变题库中某一个试题的公开状态（由公开变为不公开）
        /// </summary>
        /// <param name="libId"></param>
        public void changeTestLib(int libId)
        {
            TbTestLib tempTestLib = new TestLibDAO().GetByID(libId);
            if (tempTestLib != null)
            {
                TestLibDAO TLDao = new TestLibDAO();
                tempTestLib.IStuOpen = 0;  //改变试题的状态为不公开
                TLDao.Update(tempTestLib);
            }
        }



        /// <summary>
        /// 教师删除练习，同时删除对应的学生练习
        /// </summary>
        public int DeleteIdsPra(string ids)
        {
            try
            {
                StuPracticeDAO stuPraDAO = new StuPracticeDAO();
                TList<TbStuPractice> stuList = new TList<TbStuPractice>();
                int teaId = frontCurrentTea.GetUserID();

                new StuPracticeListDAO().Del(ids);//删除练习

                string[] praList = ids.Split(new char[] { ',' });
                foreach (var item in praList)
                {
                    TList<TbStuPractice> tempList = stuPraDAO.GetByPage(
                        "I_TeaID=" + teaId + " and I_PracticeID=" + item, 0, int.MaxValue);
                    stuList.AddRange(tempList);
                }
                stuPraDAO.Del(stuList);//删除所有练习的学生
            }
            catch (Exception ex)
            {
                //批量删除是出错
                return -2;
            }
            //批量删除成功
            return 1;
        }


        /// <summary>
        ///更新章节
        /// </summary>
        public int PutTreeNode(int id, TbTeaCatalog item)
        {


            if (id != item.Id)
            {
                //数据无效
                return -1;
            }

            try
            {
                TeaCatalogDAO catalog = new TeaCatalogDAO();
                double number = 0.0;
                string cap = string.IsNullOrEmpty(item.SCaptailName) ?
                    "" : item.SCaptailName.Substring(1, 1);
                int parentId = (int)item.IParentId;//取得父节点
                string[] str = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一",
                             "十二","十三","十四","十五","十六","十七","十八","十九","二十","二十一",
                             "二十二","二十三","二十四","二十五","二十六","二十七","二十八","二十九","三十"};   //章节
                if (str.Contains(cap))
                {
                    int temp = 0;
                    //若是章：取中间的char转为数字的标题
                    temp = Array.IndexOf(str, cap) + 1;
                    if (parentId == 0)
                    {
                        number += temp;
                    }
                    //若为节：
                    else
                    {
                        TbTeaCatalog cataTmp = catalog.GetByID(parentId);//找到所属章
                        double numbTmp = Convert.ToDouble(cataTmp.SNumber);//得到数字目录
                        number = numbTmp + Convert.ToDouble(temp)/10;
                    } 
                }
                item.SNumber = number.ToString();
                catalog.Update(item);
            }
            catch (Exception ex)
            {
                //更新数据失败
                return -2;
            }

            //更新成功
            return 1;


        }
    }
}
